package com.etrans.baf.analyse.task.swap.service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.etrans.baf.analyse.util.BaseService;
import com.etrans.baf.analyse.util.Constants;
import com.etrans.baf.analyse.util.DateUtils;
import com.etrans.baf.analyse.util.SpringWebContextUtil;
import com.etrans.baf.analyse.util.Sysconfig;
import com.etrans.baf.analyse.util.XmlReader;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.CommandResult;
import com.mongodb.DBObject;
@Service
public class EnterpriseSwapService extends BaseService{
 	@Autowired
	private MongoTemplate egovMongoTemplate;//引入配置的mongod模版
 	public EnterpriseSwapService() {
		super.masterAliases = "com.etrans.baf.analyse.task.swap.persistence.swapMapper";
  	}
  	@Override
	protected SqlSessionTemplate getMasterSessionTemplate() {
		return (SqlSessionTemplate) SpringWebContextUtil.getApplicationContext().getBean("dataSourceMasterSession");
	}
  	/**
  	 * 获取行业信息
  	 * @return
  	 */
  	private List<HashMap<String,Object>> getTradeInfo(){
		return (List<HashMap<String, Object>>) this.select("getTradeInfo", null);
  	}
	/**
	 * 业户分析
	 * @throws Exception 
	 */
	public void enterpriseSwap(String analyse_date,int num) throws Exception{
		//先删除后新增
		Date analyseDate = DateUtils.parse(analyse_date,Constants.DATE_YYYY_MM_DD);
		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("swap");
    	String table_date= DateUtils.format(analyseDate, Constants.DATE_YYMMDD);
    	if(num==0){
    		List<HashMap<String,Object>> trade = getTradeInfo();
    		if(trade!=null && trade.size()>0){
    			DBObject scope = new BasicDBObject();
                for (HashMap hashMap : trade) {
                	DBObject obj = new BasicDBObject();
                	obj.put("trade_name", hashMap.get("trade_name"));
                	obj.put("vehicle_count",0);
                	obj.put("vehicle_access_count",0);
                	obj.put("vehicle_online_count",0);
                	obj.put("alarm_vehicle_count",0);
                	obj.put("vehicle_access_rate",0.0);
                	obj.put("vehicle_online_rate",0.0);
                	obj.put("alarm_vehicle_rate",0.0);
                	obj.put("alarm_count",0.0);
                	obj.put("alarm_processed",0);
                	obj.put("overspeed_count",0);
                	obj.put("overspeed_processed",0);
                	obj.put("tired_count",0);
                	obj.put("tired_processed",0);
                	obj.put("avg_overspeed_count",0);
                	obj.put("avg_tired_count",0);
                	obj.put("alarm_processed_rate",0.0);
                	scope.put(String.valueOf(hashMap.get("id")), obj);
				}
        		Query query = Query.query(Criteria.where("analyse_date").is(analyseDate));
            	int dcount = egovMongoTemplate.remove(query,"enterprise_swap").getN();
        		mapReduceEnterprise(dirUrl, analyse_date, table_date,scope);
    		}else{
    			logger.info("没有行业信息,不让分析业户分析");
    		}
    	}else if(num==1){
    		mapReduceEnterpriseCheck(dirUrl, analyse_date, table_date);
    	}
	}
	/**
     * 业务维度中间表分析
     * @param dirUrl 文件目录地址
     * @param analyse_date yyyy-MM-dd
     * @param table_date yyMMdd
     * @throws Exception
     */
	private void mapReduceEnterprise(String dirUrl,String analyse_date,String table_date,DBObject scope) throws Exception{
		Map<String,String> exp = XmlReader.readXmlToMapReduce(dirUrl+"enterprise_swap.xml");
         if(exp!=null&& exp.size()>0){
         	DBObject command = new BasicDBObject();
        	DBObject sort = new BasicDBObject();
        	sort.put("_id",1);
        	DBObject query = new BasicDBObject();
        	query.put("analyse_date", DateUtils.parse(analyse_date, Constants.DATE_YYYY_MM_DD));
        	command.put("mapreduce","vehicle_swap");
        	command.put("query", query);
        	command.put("map",exp.get("map0"));
        	command.put("reduce",exp.get("reduce0"));
        	command.put("out","enterprise_swap_temp0"); 
        	command.put("sort", sort);//analyse_date
        	CommandResult result = egovMongoTemplate.executeCommand(command);
        	boolean ok = result.ok();
        	logger.info("业户分析第一步enterprise_swap_temp0"+(ok?"成功":"失败,原因是:"+result.getErrorMessage()));
 	        if(ok){//入库更新
 	        	command.put("mapreduce","enterprise_swap_temp0");
 	        	command.removeField("query");
 	        	command.put("map",exp.get("map"));
 	        	command.put("reduce",exp.get("reduce"));
 	        	String tradeObj = JSON.toJSONString(scope);
 	    		String finalizeStr = exp.get("finalize").replaceAll("TRADE_OBJ", tradeObj);
 				command.put("finalize",finalizeStr);
 				command.put("out","enterprise_swap_temp"); 
 				command.removeField("sort");
 	        	CommandResult result2 = egovMongoTemplate.executeCommand(command);
 	        	logger.info("业户分析第二步enterprise_swap_temp"+(result2.ok()?"成功":"失败,原因是:"+result2.getErrorMessage()));
                if(result2.ok()){
		        	String update = exp.get("update").replaceAll("DATE_YYMMDD", table_date);
	        		egovMongoTemplate.getDb().doEval(update);//追加
                }
	        }
         }
    }
	
	private void mapReduceEnterpriseCheck(String dirUrl,String analyse_date,String table_date) throws Exception{
		Map<String,String> exp = XmlReader.readXmlToMapReduce(dirUrl+"vehicle_swap_post_check.xml");
         if(exp!=null&& exp.size()>0){
         	DBObject command = new BasicDBObject();
        	DBObject sort = new BasicDBObject();
        	sort.put("_id",1);
        	DBObject query = new BasicDBObject();
        	DBObject time = new BasicDBObject();
        	time.put("$gte", DateUtils.parse(analyse_date+" 00:00:00.000"));
        	time.put("$lte", DateUtils.parse(analyse_date+" 23:59:59.999"));
        	query.put("check_time",time);
        	command.put("mapreduce","post_check_cmd");
        	command.put("query", query);
        	command.put("map",exp.get("map"));
        	command.put("reduce",exp.get("reduce"));
        	command.put("finalize",exp.get("finalize"));
        	command.put("out","vehicle_swap_post_check"); 
        	command.put("sort", sort);//analyse_date
        	CommandResult result = egovMongoTemplate.executeCommand(command);
        	boolean ok = result.ok();
        	logger.info((ok)?"vehicle_swap_post_check创建成功":"vehicle_swap_post_check创建失败:"+result.getErrorMessage());
 	        if(ok){//入库更新
	        	String update = exp.get("update").replaceAll("DATE_YYMMDD", table_date);
        		egovMongoTemplate.getDb().doEval(update);//追加
	        }
         }
    }
	/**
	 * 业务得分设置
	 * @param analyse_date
	 * @throws Exception
	 */
	public void updateScore(String analyse_date) throws Exception{
		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("swap");
		Map<String,String> map = XmlReader.readXmlToMapReduce(dirUrl+"score_swap.xml");
        if(map!=null){
        	String last_date = DateUtils.getAnalyseDate(analyse_date, -1);//取上一天
        	String update = map.get("enterpriseScore").replaceAll("DATE_YYYY_MM_DD", last_date);
    		egovMongoTemplate.getDb().doEval(update);
    		logger.info("----修改区域得分--------");
        }
	}
	
	/**
	 * 周月季年分析
	 * @param analyse_date 分析的首日
	 * @type 0周 1月 2季度 3年度
	 * @throws Exception
	 */
	public void enterWMSY(String start_date,String end_date,int type) throws Exception{
		//Date startDate = DateUtils.parse(start_date,Constants.DATE_YYYY_MM_DD);
		//Date endDate = DateUtils.parse(end_date,Constants.DATE_YYYY_MM_DD);
		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("swap");
		//String YYMMDD = DateUtils.format(startDate, Constants.DATE_YYMMDD);
		List<HashMap<String,Object>> trade = getTradeInfo();
		if(trade!=null && trade.size()>0){
			DBObject scope = new BasicDBObject();
            for (HashMap hashMap : trade) {
            	DBObject obj = new BasicDBObject();
            	obj.put("trade_name", hashMap.get("trade_name"));
            	obj.put("vehicle_count",0);
            	obj.put("vehicle_access_count",0);
            	obj.put("vehicle_online_count",0);
            	obj.put("alarm_vehicle_count",0);
            	obj.put("vehicle_access_rate",0.0);
            	obj.put("vehicle_online_rate",0.0);
            	obj.put("alarm_vehicle_rate",0.0);
            	obj.put("alarm_count",0.0);
            	obj.put("alarm_processed",0);
            	obj.put("overspeed_count",0);
            	obj.put("overspeed_processed",0);
            	obj.put("tired_count",0);
            	obj.put("tired_processed",0);
            	obj.put("avg_overspeed_count",0);
            	obj.put("avg_tired_count",0);
            	obj.put("alarm_processed_rate",0.0);
            	scope.put(String.valueOf(hashMap.get("id")), obj);
			}
            //String analyse_date = DateUtils.getAnalyseDate(start_date,-1);//mongodb 日期-8小时
            //analyseWMSY(dirUrl, startDate, endDate, scope, type,YYMMDD,analyse_date);
            analyseWeekMonth(dirUrl, start_date, end_date, scope, type);
		}else{
			logger.info("没有行业信息,不让分析业户月 周 季度 年表");
		}    	 
	}
	/**
	 * 周 月 当月 季度 年的业户分析
	 * @throws Exception 
	 */
	private void analyseWeekMonth(String dirUrl,String startDate,String endDate,DBObject scope,int type) throws Exception{
		Map<String,String> exp = XmlReader.readXmlToMapReduce(dirUrl+"enterprise_swap_weekMonth.xml");
        if(exp!=null&& exp.size()>0){
        	DBObject command = new BasicDBObject();
           	DBObject sort = new BasicDBObject();
           	sort.put("_id",1);
           	DBObject query = new BasicDBObject();
           	String mrtable="";
           	String out_table="";
            String insert_table="";
            String YYYY_MM_DD_S="";
            String YYYY_MM_DD_E="";
            String YYMMDD="";
            String area_table = "";
           	if(type==Constants.ENTERPRISE_ANALYSE_W){
           		query.put("analyse_date",DateUtils.parse(startDate, Constants.DATE_YYYY_MM_DD));
           		mrtable="vehicle_swap_week";
           		out_table="enterprise_swap_temp_week";
        		insert_table="enterprise_swap_week";
        		YYMMDD=startDate.substring(2,10).replaceAll("-", "");
        		YYYY_MM_DD_S=DateUtils.getAnalyseDate(startDate, -1);//前一天
        		YYYY_MM_DD_E=DateUtils.getAnalyseDate(endDate, -1);//前一天
        		area_table="area_swap_week";
           	}else if(type==Constants.ENTERPRISE_ANALYSE_M){
           		query.put("analyse_date",DateUtils.parse(endDate.substring(0,7)+"-01", Constants.DATE_YYYY_MM_DD));
           		mrtable="vehicle_swap_month";
           		out_table="enterprise_swap_temp_month";
        		insert_table="enterprise_swap_month";
        		YYMMDD=endDate.substring(2,7).replaceAll("-", "")+"01";
        		YYYY_MM_DD_S=DateUtils.getAnalyseDate(startDate, -1);//前一天
        		YYYY_MM_DD_E=DateUtils.getAnalyseDate(endDate, -1);//前一天
        		area_table="area_swap_month";
           	}else if(type==Constants.ENTERPRISE_ANALYSE_CM){
           		mrtable="vehicle_swap_curMonth";
        		insert_table="enterprise_swap_curMonth";
        		out_table="enterprise_swap_temp_curMonth";
        		area_table="area_swap_curMonth";
        		String current_mon_day = DateUtils.format(new Date(),Constants.DATE_YYYY_MM_DD);
    			String day = current_mon_day.substring(current_mon_day.length()-2,current_mon_day.length());
    			if(Integer.parseInt(day)<=25){//当前月  25分析
    				YYMMDD=endDate.substring(2,7).replaceAll("-", "")+"01";
    	    		YYYY_MM_DD_S=DateUtils.getAnalyseDate(startDate, -1);//前一天
    	    		
    			}else{//分析下个月
    				String  startDateStr=DateUtils.nextMonthFirstDate();
    				Date start=DateUtils.parse(startDateStr,Constants.DATE_YYYY_MM_DD);
    	    		YYMMDD = DateUtils.format(start, Constants.DATE_YYMMDD);
    	    		YYYY_MM_DD_S=DateUtils.getAnalyseDate(startDate, -1);
    			}
    			String beforeone  = DateUtils.getAnalyseDate(current_mon_day, -1);//前一天
        		YYYY_MM_DD_E=DateUtils.getAnalyseDate(beforeone, -1);//实际的分析结束日期(mongodb里面是前一天的16:00结束)
        	}
           	String outtable0="enterprise_"+type;
           	command.put("mapreduce",mrtable);
           	command.put("query", query);
           	command.put("map",exp.get("map0"));
           	command.put("reduce",exp.get("reduce0"));
           	command.put("out",outtable0); 
           	command.put("sort", sort);
           	CommandResult result = egovMongoTemplate.executeCommand(command);
           	boolean ok = result.ok();
            logger.info("创建业户"+outtable0+(ok?"成功":"失败:"+result.getErrorMessage()));
           	if(ok){//入库更新
           		    command.put("mapreduce",outtable0);
           			command.removeField("query");
           			command.put("map",exp.get("map"));
                   	command.put("reduce",exp.get("reduce"));
                   	String tradeObj = JSON.toJSONString(scope);
            		String finalizeStr = exp.get("finalize").replaceAll("TRADE_OBJ", tradeObj);
            		command.put("finalize",finalizeStr);
            		command.put("out",out_table); 
            		command.removeField("sort");
            		CommandResult result2 = egovMongoTemplate.executeCommand(command);
                    logger.info("创建业户分析"+out_table+(result2.ok()?"成功":"失败:"+result2.getErrorMessage()));
                    if(result2.ok()){
	    	        	String update = exp.get("update").replaceAll("DATE_YYMMDD",YYMMDD).replaceAll("PARAM_ENTERPRISE_INSERT", insert_table).replaceAll("PARAM_ENTERPRISE_TABLE", out_table).replaceAll("YYYY_MM_DD_S", YYYY_MM_DD_S).replaceAll("YYYY_MM_DD_E", YYYY_MM_DD_E).replaceAll("AREA_TABLE", area_table).replaceAll("VEHICLE_TABLE", mrtable);
	    	        	egovMongoTemplate.getDb().doEval(update);//追加
	            	    logger.info("分析成功"+out_table);
                    }
    	     }
         }
	}
	/**
	 * 周 月 当月 季度 年的业户分析
	 * @throws Exception 
	 */
	private void analyseWMSY(String dirUrl,Date startDate,Date endDate,DBObject scope,int type,String YYMMDD,String analyse_date) throws Exception{
		Map<String,String> exp = XmlReader.readXmlToMapReduce(dirUrl+"enterprise_swap_WMSY.xml");
        if(exp!=null&& exp.size()>0){
        	DBObject command = new BasicDBObject();
       	DBObject sort = new BasicDBObject();
       	sort.put("_id",1);
       	DBObject query = new BasicDBObject();
       	DBObject time = new BasicDBObject();
       	time.put("$gte", startDate);
       	time.put("$lte", endDate);
       	query.put("analyse_date",time);
       	command.put("mapreduce","enterprise_swap");
       	command.put("query", query);
       	command.put("map",exp.get("map"));
       	command.put("reduce",exp.get("reduce"));
       	String tradeObj = JSON.toJSONString(scope);
		String finalizeStr = exp.get("finalize").replaceAll("TRADE_OBJ", tradeObj);
		command.put("finalize",finalizeStr);
    	String out_table="";
        String insert_table="";
    	if(type==Constants.ENTERPRISE_ANALYSE_W){
    		out_table="enterprise_swap_temp_week";
    		insert_table="enterprise_swap_week";
    	}else if(type==Constants.ENTERPRISE_ANALYSE_M){
    		out_table="enterprise_swap_temp_month";
    		insert_table="enterprise_swap_month";
    		startDate=DateUtils.parse(DateUtils.format(endDate, Constants.DATE_YYYY_MM)+"-01", Constants.DATE_YYYY_MM_DD);
    		YYMMDD = DateUtils.format(startDate, Constants.DATE_YYMMDD);
    		String  startDateStr= DateUtils.format(startDate, Constants.DATE_YYYY_MM_DD);
    		analyse_date=DateUtils.getAnalyseDate(startDateStr,-1);//mongodb 日期-8小时
    	}else if(type==Constants.ENTERPRISE_ANALYSE_S){
    		out_table="enterprise_swap_temp_season";
    		insert_table="enterprise_swap_season";
    	}else if(type==Constants.ENTERPRISE_ANALYSE_Y){
    		insert_table="enterprise_swap_year";
    		out_table="enterprise_swap_temp_year";
    	}else if(type==Constants.ENTERPRISE_ANALYSE_CM){
    		insert_table="enterprise_swap_curMonth";
    		out_table="enterprise_swap_temp_curMonth";
    		String current_mon_day = DateUtils.format(new Date(),Constants.DATE_YYYY_MM_DD);
			String day = current_mon_day.substring(current_mon_day.length()-2,current_mon_day.length());
			if(Integer.parseInt(day)<=25){//当前月
				startDate=DateUtils.parse(DateUtils.format(endDate, Constants.DATE_YYYY_MM)+"-01", Constants.DATE_YYYY_MM_DD);
	    		YYMMDD = DateUtils.format(startDate, Constants.DATE_YYMMDD);
	    		String  startDateStr= DateUtils.format(startDate, Constants.DATE_YYYY_MM_DD);
	    		analyse_date=DateUtils.getAnalyseDate(startDateStr,-1);//mongodb 日期-8小时
			}else{//分析下个月
				String  startDateStr=DateUtils.nextMonthFirstDate();
				startDate=DateUtils.parse(startDateStr,Constants.DATE_YYYY_MM_DD);
	    		YYMMDD = DateUtils.format(startDate, Constants.DATE_YYMMDD);
	    		analyse_date=DateUtils.getAnalyseDate(startDateStr,-1);//mongodb 日期-8小时
			}
    	}
       	command.put("out",out_table); 
       	command.put("sort", sort);
       	CommandResult result = egovMongoTemplate.executeCommand(command);
       	boolean ok = result.ok();
        logger.info("创建区域"+out_table+(ok?"成功":"失败:"+result.getErrorMessage()));
       	if(ok){//入库更新
				Query rquery = Query.query(Criteria.where("analyse_date").is(startDate));
        	    int dcount = egovMongoTemplate.remove(rquery,insert_table).getN();
        	    logger.info("删除"+insert_table+"数据"+dcount);
	        	String update = exp.get("update").replaceAll("DATE_YYMMDD",YYMMDD).replaceAll("PARAM_ENTERPRISE_INSERT", insert_table).replaceAll("PARAM_ENTERPRISE_TABLE", out_table).replaceAll("DATE_YY_MM_DD", analyse_date);
	        	egovMongoTemplate.getDb().doEval(update);//追加
        	    logger.info("分析成功"+out_table);
	     }
        }
	}
	/**
	 * 周月 季度 当月 年分析表得分
	 */
	public void updateScoreWMSY(String analyse_date,int type) throws Exception{
		String dirUrl=System.getProperty("analyse")+Sysconfig.getPropValueByCode("swap");
		Map<String,String> map = XmlReader.readXmlToMapReduce(dirUrl+"score_WMSY.xml");
        if(map!=null){
        	String insert_table="";
        	String AREA_TABLE="";
        	if(type==Constants.ENTERPRISE_ANALYSE_W){
        		insert_table="enterprise_swap_week";
        		AREA_TABLE="area_swap_week";
        	}else if(type==Constants.ENTERPRISE_ANALYSE_M){
        		insert_table="enterprise_swap_month";
        		AREA_TABLE="area_swap_month";
        	}else if(type==Constants.ENTERPRISE_ANALYSE_S){
        		insert_table="enterprise_swap_season";
        		AREA_TABLE="area_swap_season";

        	}else if(type==Constants.ENTERPRISE_ANALYSE_Y){
        		AREA_TABLE="area_swap_year";
        		insert_table="enterprise_swap_year";
        	}else if(type==Constants.ENTERPRISE_ANALYSE_CM){
        		insert_table="enterprise_swap_curMonth";
        		AREA_TABLE="area_swap_curMonth";
        	}
        	String last_date = DateUtils.getAnalyseDate(analyse_date, -1);//取上一天
         	String update = map.get("enterpriseScore").replaceAll("DATE_YYYY_MM_DD", last_date).replaceAll("ENTERPRISE_TABLE", insert_table).replaceAll("AREA_TABLE", AREA_TABLE);
    		egovMongoTemplate.getDb().doEval(update);
    		logger.info("----修改"+insert_table+"业户得分--------");
        }
	}
}
